package view.diaLogView;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.TextView;
import android.widget.Toast;
import com.example.administrator.text.R;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import app.MyApplication;
import data.SharedPreferencesUtils;
import util.GreenTreeNetworkUtil;
import util.HomeUtil;
import util.LogUtil;
import util.NetUtils;
import util.RequestDataCallback;
import util.StringUtil;
import util.Url;

/**
 * Created by liuxiaobin on 2016/9/5.
 *扫一扫登录PC端
 */
public class ScanDialog extends Dialog{
        private Context mContext;
        private String mID,mToken,mSessionId,mUrl,mType,mBand;
        private ScanDialog mScanDialog;
        private TextView tvhint,tvhint1;
        private String url = "";
        @Override public void show() {
            Window window = getWindow();
            window.setGravity(Gravity.BOTTOM);
            window.setWindowAnimations(R.style.share_style);
            super.show();
        }

        public ScanDialog(Context context,String id,String token,String sessionId,String type,String url) {
            super(context, R.style.scan_dialog);
            mScanDialog = this;
            this.mContext = context;
            this.mToken = token;
            this.mID = id;
            this.mSessionId = sessionId;
            this.mType = type;
            this.mUrl = url;

        }

        @Override protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            init();
        }

        private void init() {
            ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            params.width = mContext.getResources().getDisplayMetrics().widthPixels;
            params.height = mContext.getResources().getDisplayMetrics().heightPixels;
            LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View mView = inflater.inflate(R.layout.scan_dialog, null);
            TextView TVEntryOneself = (TextView)mView.findViewById(R.id.tv_dialog_scanentryOneself);   //本人登录
            TextView TVScan = (TextView)mView.findViewById(R.id.tv_dialog_scan);                   //取消登录
            tvhint = (TextView)mView.findViewById(R.id.text_scan_hint);
            tvhint1 = (TextView)mView.findViewById(R.id.text_scan_hint1);
            LogUtil.eE("","..........................1");
            if(mType.equals("appAccreditNet")){
                initData();
            }else if(mType.equals("pcAccreditNet")){
                tvhint.setText("授权联网");
                TVEntryOneself.setText("授权自己");
            }else if(mType.equals("bamlogin")){
                tvhint.setText("授权登录");
                tvhint1.setText("授权后台系统登录");
            }


            TVEntryOneself.setOnClickListener(new View.OnClickListener() {
                @Override public void onClick(View v) {
                    if(mType.equals("bamlogin")){
                        getJumapAltair();
                    }else if(mType.equals("appAccreditNet")){
                        getPhoneAccreditNet();
                    }else if(mType.equals("pcAccreditNet")){
                        getPcOneselfAccreditNet();
                    }else if(mType.equals("NewProtect")){
                        phonelogin();
                    }

                }
            });

            TVScan.setOnClickListener(new View.OnClickListener() {
                @Override public void onClick(View v) {mScanDialog.dismiss();}});
            LogUtil.eE("","..........................2");
            setContentView(mView, params);
        }

    /**
     * 初始化数据
     */
    private void initData() {
        mBand = "";
        HashMap<String, Object> map = new HashMap<>();
        map.put("sessionid",mSessionId);
        String stringJson = StringUtil.getStringUtilNew().hashMapToJson(map); //参数包
        long time = StringUtil.getStringUtilNew().getTimeCurrent();
        String stirngSign = StringUtil.getStringUtilNew().getSign(Url.mStirngAccredit_infoNetQr,stringJson,mToken,mID,time);
        Map map1 = StringUtil.getStringUtilNew().getMapNew(mContext,stringJson,mToken,mID,Url.mStirngAccredit_infoNetQr,stirngSign,time);
        LogUtil.eE("",MyApplication.getApp().getFWQString()+"    "+mSessionId);
        if(NetUtils.getInstance(mContext).getNetWorkTeyt() == 0){
            url = Url.getUrlNew().getAppIP();
        }else {
            url = MyApplication.getApp().getFWQString();
        }
        GreenTreeNetworkUtil.getInstance().doPost(mContext,url,1,map1,new RequestDataCallback() {
            @Override public void onSuccess(String response) {
                try {
                    JSONObject json = new JSONObject(response);
                    LogUtil.eE("",response);
                    if(json.getInt("code") == 1){
                        String phone = json.getString("phone");
                        String nickname = json.getString("nickname");
                        String netTime = "";
                        mBand = json.getString("band");
                        tvhint.setText("授权联网");
                        if(Double.parseDouble(json.getString("netTime"))>1){
                            netTime = json.getString("netTime")+"小时";
                        }else {
                            netTime = Double.parseDouble(json.getString("netTime"))*60+"分钟";
                        }
                        tvhint1.setText("授权"+nickname+":"+phone+"联网"+netTime);
                    }else if(json.getInt("code") == 0){
                        if(json.getInt("reason") == 1){
                            tvhint.setText("授权联网");
                            tvhint1.setText("二维码失效");
                        }else if(json.getInt("reason") == 2){
                            tvhint.setText("授权联网");
                            tvhint1.setText("您没有权限授权他人联网");
                        }
                    }else if(json.getInt("code") == -1){
                        Toast.makeText(mContext,mContext.getString(R.string.FWQ),Toast.LENGTH_SHORT).show();
                    }else if (json.getInt("code") == -2) {
                        CrowdRetunDialog crowdRetunDialog = new CrowdRetunDialog(mContext);
                        crowdRetunDialog.show();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override public void onFailure(Throwable error) {
                StringUtil.getStringUtilNew().getExceptionCode(mContext,error.toString());
            }
        });
    }

    /**
     * 登入管理后台的请求
     */
    private void getJumapAltair(){
        Map<String,Object> map = new HashMap();
        map.put("sessionid",mSessionId);
        map.put("userid",mID);
        map.put("token",mToken);
        LogUtil.eE("","url..."+mUrl);
        GreenTreeNetworkUtil.getInstance().doPost(mContext,mUrl,1,map, new RequestDataCallback() {
            @Override public void onSuccess(String response) {
                LogUtil.eE("",response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    int code = jsonObject.getInt("code");
                    LogUtil.eE("code","code"+code+"mSessionId"+mSessionId+"usrid"+mID+"token"+mToken);
                    mScanDialog.dismiss();
                    if (code == 0){
                        Toast.makeText(mContext,R.string.scan_no,Toast.LENGTH_SHORT).show();
                    }else if(code == 1){
                        Toast.makeText(mContext,R.string.scan_yes,Toast.LENGTH_SHORT).show();
                    }else if(code == 2){
                        Toast.makeText(mContext, R.string.scan2_no,Toast.LENGTH_SHORT).show();
                    }

                } catch (JSONException e) {e.printStackTrace();
                    Toast.makeText(mContext, R.string.scan_no,Toast.LENGTH_SHORT).show();
                    mScanDialog.dismiss();
                   }
            }

            @Override public void onFailure(Throwable error) {
                StringUtil.getStringUtilNew().getExceptionCode(mContext,error.toString());
                mScanDialog.dismiss();
            }
        });
    }

    /**
     * 手机的授权上网
     */
    private void getPhoneAccreditNet(){
        if(mBand.equals("")){
            return;
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("sessionid",mSessionId);
        map.put("band",mBand);
        String stringJson = StringUtil.getStringUtilNew().hashMapToJson(map); //参数包
        long time = StringUtil.getStringUtilNew().getTimeCurrent();
        String stirngSign = StringUtil.getStringUtilNew().getSign(Url.mStirngAccredit_verifyNetQr,stringJson,mToken,mID,time);
        Map map1 = StringUtil.getStringUtilNew().getMapNew(mContext,stringJson,mToken,mID,Url.mStirngAccredit_verifyNetQr,stirngSign,time);
        if(NetUtils.getInstance(mContext).getNetWorkTeyt() == 0){
            url = Url.getUrlNew().getAppIP();
        }else {
            url = MyApplication.getApp().getFWQString();
        }
        GreenTreeNetworkUtil.getInstance().doPost(mContext,url,1,map1, new RequestDataCallback() {
            @Override public void onSuccess(String response) {
                try {
                    JSONObject json = new JSONObject(response);
                    LogUtil.eE("",response);
                    if(json.getInt("code") == 1){
                        mScanDialog.dismiss();

                        final RetunDialog retunDialog = new RetunDialog(mContext,"",6,true);
                        retunDialog.show();
                        HomeUtil.getHemeUtilNew().getHandlerNew().postDelayed(new Runnable() {
                            @Override public void run() {
                                retunDialog.dismiss();
                            }
                        },1000);
                    }else if (json.getInt("code") == -2) {
                        CrowdRetunDialog crowdRetunDialog = new CrowdRetunDialog(mContext);
                        crowdRetunDialog.show();
                    }else if (json.getInt("code") == 0){
                        if(json.getInt("reason") == 1){
                            Toast.makeText(mContext,"二维码失效，请重新生成",Toast.LENGTH_SHORT).show();
                        }else if(json.getInt("reason") == 2){
                            Toast.makeText(mContext,"请检查自己是否有权限",Toast.LENGTH_SHORT).show();
                        }
                    }
                    else if(json.getInt("code") == -1){
                        Toast.makeText(mContext,mContext.getString(R.string.FWQ),Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override public void onFailure(Throwable error) {
                StringUtil.getStringUtilNew().getExceptionCode(mContext,error.toString());
            }
        });
    }

    /**
     * pc端自己联网
     */
    private void getPcOneselfAccreditNet(){
        HashMap<String, Object> map = new HashMap<>();
        map.put("sessionid",mSessionId);
        map.put("userid",mID);
        String stringJson = StringUtil.getStringUtilNew().hashMapToJson(map); //参数包
        long time = StringUtil.getStringUtilNew().getTimeCurrent();
        String stirngSign = StringUtil.getStringUtilNew().getSign(Url.mStirngpcNetQr_pcQrselfNet,stringJson,mToken,mID,time);
        Map map1 = StringUtil.getStringUtilNew().getMapNew(mContext,stringJson,mToken,mID,Url.mStirngpcNetQr_pcQrselfNet,stirngSign,time);
        if(NetUtils.getInstance(mContext).getNetWorkTeyt() == 0){
            url = Url.getUrlNew().getAppIP();
        }else {
            url = MyApplication.getApp().getFWQString();
        }
        GreenTreeNetworkUtil.getInstance().doPost(mContext,url,1,map1, new RequestDataCallback() {
            @Override public void onSuccess(String response) {
                try {
                    JSONObject json = new JSONObject(response);
                    LogUtil.eE("",response);
                    if(json.getInt("code") == 1){
                        mScanDialog.dismiss();
                        final RetunDialog retunDialog = new RetunDialog(mContext,"",6,true);
                        retunDialog.show();
                        HomeUtil.getHemeUtilNew().getHandlerNew().postDelayed(new Runnable() {
                            @Override public void run() {
                                retunDialog.dismiss();
                            }
                        },1000);
                    }else if (json.getInt("code") == -2) {
                        CrowdRetunDialog crowdRetunDialog = new CrowdRetunDialog(mContext);
                        crowdRetunDialog.show();
                    } else if (json.getInt("code") == 0){
                        if(json.getInt("reason") == 1){
                            Toast.makeText(mContext,"二维码失效，请重新生成",Toast.LENGTH_SHORT).show();
                        }else if(json.getInt("reason") == 2){
                            Toast.makeText(mContext,"请检查自己是否有权限",Toast.LENGTH_SHORT).show();
                        }
                    }
                     else if(json.getInt("code") == -1){
                        Toast.makeText(mContext,mContext.getString(R.string.FWQ),Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override public void onFailure(Throwable error) {
                StringUtil.getStringUtilNew().getExceptionCode(mContext,error.toString());
            }
        });
    }

    public void phonelogin (){
        HashMap<String, Object> map = new HashMap<>();
        String phone = (String) SharedPreferencesUtils.getParam(mContext,HomeUtil.mHUWePhone,"");
        map.put("uuid",mSessionId);
        map.put("userid",mID);
        map.put("phone",phone);
        LogUtil.eE("","phonelogin...uuid"+mSessionId+"...userid..."+mID+"...phone..."+phone);
        GreenTreeNetworkUtil.getInstance().doPost(mContext,Url.mATIAIRIP+Url.getUrlNew().Phonelogin,1,map, new RequestDataCallback() {
            @Override public void onSuccess(String response) {
                if(response.equals("true")){
                    mScanDialog.dismiss();
                    Toast.makeText(mContext, "授权成功", Toast.LENGTH_SHORT).show();
                }else {
                    Toast.makeText(mContext, "授权失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override public void onFailure(Throwable error) {
                StringUtil.getStringUtilNew().getExceptionCode(mContext,error.toString());
            }
        });
    }
}
